/*
 * Copyright (c) 2011. This file is public under GPLv3 license.
 * For more information about license please refer to http://www.gnu.org/licenses/gpl.html
 */

package com.freetools.watchdog.commands;

import com.freetools.watchdog.model.CommandName;
import com.freetools.watchdog.model.ICommand;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.Map;

/**
 * Date: Feb 19, 2011
 *
 * @author Michael Morozov
 */
public class CommandFactory
{
    private static final Logger log = Logger.getLogger(CommandFactory.class);
    private static Map<String, Class<? extends ICommand>> commandsClasses = new HashMap<String, Class<? extends ICommand>>();
    private static Map<Class<? extends ICommand>, String[]> commandNames = new HashMap<Class<? extends ICommand>, String[]>();

    public static String[] getCommandsNames()
    {
        String[] result = new String[commandsClasses.keySet().size()];
        commandsClasses.keySet().toArray(result);
        return result;
    }

    static
    {
        register(FileCmd.class);
        register(ColumnsCmd.class);
        register(QueryCmd.class);
        register(SortCmd.class);
        register(ParseCmd.class);
        register(HelpCmd.class);
        register(RunCmd.class);
        register(SpoolCmd.class);
        register(ExitCmd.class);
    }

    public static void register(Class<? extends ICommand> clazz)
    {
        log.debug("registered command = " + clazz);
        CommandName annotation = clazz.getAnnotation(CommandName.class);
        if (annotation != null)
        {
            commandNames.put(clazz, annotation.value());

            for (String value : annotation.value())
            {
                commandsClasses.put(value, clazz);
            }

        } else
        {
            log.warn("Class with name " + clazz + " does not have annotation " + CommandName.class +
                    ". So this class will not be registered");
        }
    }

    public static ICommand createCommand(String commandName)
    {
        Class<? extends ICommand> commandClass = commandsClasses.get(commandName);
        try
        {
            return commandClass.newInstance();
        } catch (Exception e)
        {
            log.error("Cannot create command", e);
        }

        return null;
    }

}
